package com.kinon.market.view;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.kinon.market.R;
import com.kinon.market.adapter.CaidanAdapter;
import com.kinon.market.entity.CaidanEntity;
import com.kinon.market.entity.ItemBean;
import com.kinon.market.entity.KVP;
import com.kinon.market.tools.HttpTools;
import com.kinon.market.tools.MyShowDialog;
import com.kinon.market.tools.NetWorkUtil;
import com.kinon.market.tools.SendShopList;
import com.kinon.market.tools.ToastUtil;
import com.kinon.market.tools.Utility;
import com.loopj.android.http.JsonHttpResponseHandler;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import sunmi.ds.DSKernel;

public class DingdandetialActivity extends Activity {

    /**
     * 获得数据
     */
    ArrayList<CaidanEntity> infolist;
    //副屏显示的菜品列表
    List<ItemBean> items;
    //副屏的取餐编号和共计
    List<KVP> sm;
    HttpTools httptools = null;
    int shuliang;
    String id;
    DSKernel mDSKernel;// SDK核心类
    private CaidanAdapter caidanAdapter;
    private TextView tv_name;
    private TextView tv_bianhao;
    private TextView tv_time;
    private TextView tv_amount;
    private TextView tv_heji;
    private TextView tv_fanhui;
    private Button btn_queren;
    /**
     * 菜单列表
     */
    private ListView lv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dingdandetial);
        initRes();
    }

    private void initRes() {
        lv = (ListView) findViewById(R.id.lv_caipin);
        tv_name = (TextView) findViewById(R.id.tv_name);
        tv_bianhao = (TextView) findViewById(R.id.tv_bianhao);
        tv_time = (TextView) findViewById(R.id.tv_time);
        tv_amount = (TextView) findViewById(R.id.tv_amount);
        tv_heji = (TextView) findViewById(R.id.tv_heji);
        tv_fanhui = (TextView) findViewById(R.id.tv_fanhui);
        tv_fanhui.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                finish();
            }
        });
        btn_queren = (Button) findViewById(R.id.btn_queren);
        btn_queren.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Queren();
            }
        });
        mDSKernel = DSKernel.newInstance();//副屏初始化
        Caidan();
    }

    /**
     * 订单详情
     */
    private void Caidan() {
        if (!NetWorkUtil.isNetwork(getApplicationContext())) {
            ToastUtil toastUtil = new ToastUtil();
            toastUtil.Short(getApplicationContext(), "  " + "当前网络不可用")
                    .setToastBackground(Color.WHITE, 0).show();
            return;
        }
        infolist = new ArrayList<CaidanEntity>();
        items = new ArrayList<>();
        sm = new ArrayList<>();
        SharedPreferences sp = getSharedPreferences("spReg",
                Context.MODE_PRIVATE);
        String token = sp.getString("data", "");
        String dayno = getIntent().getStringExtra("dayno");
        Log.i("info", "dayno---" + dayno);
        Log.i("info", "data---" + token);
        if (httptools == null) {
            httptools = new HttpTools(getApplicationContext());
        }
        httptools.getQuCanDetail(token, "", dayno, "", new JsonCaidan());

    }

    private void Queren() {
        if (!NetWorkUtil.isNetwork(DingdandetialActivity.this)) {
            Toast.makeText(DingdandetialActivity.this, "当前网络不可用", Toast.LENGTH_SHORT).show();
            return;
        }
        SharedPreferences sp = getSharedPreferences("spReg",
                Context.MODE_PRIVATE);
        String token = sp.getString("data", "");
        if (httptools == null) {
            httptools = new HttpTools(getApplicationContext());
        }
        httptools.updateOrder(token, id, "2", new JsonQueren());
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (hasFocus) {
            View decorView = getWindow().getDecorView();
            decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_FULLSCREEN);
        }
    }

    public class JsonCaidan extends JsonHttpResponseHandler {
        @Override
        public void onStart() {
            MyShowDialog.showLoadingDialog(DingdandetialActivity.this, "请稍后....");
            super.onStart();
        }

        @Override
        public void onSuccess(int statusCode, Header[] headers,
                              JSONObject response) {
            // TODO Auto-generated method stub
            super.onSuccess(statusCode, headers, response);
            MyShowDialog.closeLoadingDialog();
            try {
                Log.i("zq", response.toString());
                boolean code = response.getBoolean("code");
                String msg = response.getString("msg");
                if (code) {
                    Log.i("zq", "订单详情---" + response.toString());
                    JSONObject object = response.getJSONObject("data");
                    id = object.getString("id");
                    String username = object.getString("name");
                    String take_time = object.getString("take_time");
                    String book_time = object.getString("book_time");
                    String dayno = object.getString("dayno");
                    //					String paymodeid = object.getString("paymodeid");
                    String total = object.getString("total");
                    String orderno = object.getString("orderno");
                    String state = object.getString("state");
                    //添加副屏末尾信息
                    sm.add(new KVP("取餐编号", dayno));
                    sm.add(new KVP("共计", total));
                    JSONArray array = object.getJSONArray("details");
                    for (int j = 0; j < array.length(); j++) {
                        JSONObject details = array.getJSONObject(j);
                        String caipinid = details.getString("id");
                        String name = details.getString("name");
                        String amount = details.getString("amount");
                        String price = details.getString("price");
                        String totalprice = details.getString("total");
                        shuliang += Integer.parseInt(amount);

                        //添加副屏列表信息
                        items.add(new ItemBean(caipinid, name, price, amount, totalprice));
                        infolist.add(new CaidanEntity(caipinid, amount, name, price, 1));
                    }
                    if (state.equals("1")) {
                        btn_queren.setText("确认收货");
                    } else if (state.equals("2")) {
                        btn_queren.setText("已完成");
                    }
                    tv_name.setText(username);
                    tv_amount.setText("" + shuliang);
                    tv_heji.setText(total);
                    tv_bianhao.setText(dayno);
                    tv_time.setText(book_time);
                    //					tv_heji.setText(total);
                    caidanAdapter = new CaidanAdapter(getApplicationContext(), infolist);
                    lv.setAdapter(caidanAdapter);
                    lv.setDivider(null);
                    Log.i("zq", "item1-------" + items);
                    Utility.setListViewHeightBasedOnChildren(lv);
                    //向副屏发送数据
                    SendShopList sendShopList = new SendShopList(getApplicationContext(), mDSKernel, items, sm);
                    sendShopList.getInstance(getApplicationContext(), mDSKernel, items, sm);
                    sendShopList.send(false, "");
                } else {
                    Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
                }

            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
            super.onFailure(statusCode, headers, throwable, errorResponse);
            MyShowDialog.closeLoadingDialog();
            Toast.makeText(DingdandetialActivity.this,
                    "网络请求失败", Toast.LENGTH_SHORT).show();
            finish();
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
            super.onFailure(statusCode, headers, responseString, throwable);
            MyShowDialog.closeLoadingDialog();
            Log.w("DDDA - caidan", throwable.toString());
        }
    }

    public class JsonQueren extends JsonHttpResponseHandler {

        @Override
        public void onSuccess(int statusCode, Header[] headers,
                              JSONObject response) {
            // TODO Auto-generated method stub
            super.onSuccess(statusCode, headers, response);
            try {
                Log.i("zq", response.toString());
                boolean code = response.getBoolean("code");
                String msg = response.getString("msg");
                if (code) {
                    Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent(DingdandetialActivity.this, WancanpayresultActivity.class);
                    startActivity(intent);
                    finish();
                } else {
                    Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
                }

            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
            super.onFailure(statusCode, headers, throwable, errorResponse);
            Toast.makeText(DingdandetialActivity.this,
                    "网络请求失败", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
            super.onFailure(statusCode, headers, responseString, throwable);
            Log.w("DDDA - QUEREN", throwable.toString());
        }
    }


}
